Dart List operator []
Syntax & Examples
Syntax of List.operator []
The syntax of List.operator [] operator is:
operator [](int index) → EThis operator [] operator of List the object at the given index in the list.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
index | required | the index of the object to retrieve from the list |
✐ Examples
1 Retrieve element at index 2 from a list of numbers
In this example,
- We create a list
numberscontaining integers. - We use the
[]operator to retrieve the element at index 2. - The element at index 2 is assigned to the variable
element. - We print the value of
elementto standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int element = numbers[2];
print('Element at index 2: $element');
}Output
Element at index 2: 3
2 Retrieve element at index 1 from a list of characters
In this example,
- We create a list
characterscontaining characters. - We use the
[]operator to retrieve the element at index 1. - The element at index 1 is assigned to the variable
element. - We print the value of
elementto standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c'];
String element = characters[1];
print('Element at index 1: $element');
}Output
Element at index 1: b
3 Retrieve element at index 0 from a list of names
In this example,
- We create a list
namescontaining strings. - We use the
[]operator to retrieve the element at index 0. - The element at index 0 is assigned to the variable
element. - We print the value of
elementto standard output.
Dart Program
void main() {
List<String> names = ['Alice', 'Bob', 'Charlie'];
String element = names[0];
print('Element at index 0: $element');
}Output
Element at index 0: Alice
Summary
In this Dart tutorial, we learned about operator [] operator of List: the syntax and few working examples with output and detailed explanation for each example.